package com.example.javaee.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.javaee.dao.CourseMapper;
import com.example.javaee.dao.GradeMapper;
import com.example.javaee.domain.Course;
import com.example.javaee.domain.Grade;
import com.example.javaee.exception.LoginException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;

@Service
public class GradeService {

    @Autowired
    GradeMapper gradeMapper;

    @Autowired
    CourseMapper courseMapper;

    /**
     * 存储评分信息
     */
    public boolean saveGrade(Grade grade) throws LoginException {
        if(grade.getCourseId()==null||grade.getUserId()==null){
            throw new LoginException("保存评分失败，缺少用户或评分课程");
        }

        Grade existGrade=gradeMapper.selectByUserAndCourse(grade.getUserId(), grade.getCourseId());
        if(existGrade!=null) {
            throw new LoginException("该用户已评价过该课程");
        }
        gradeMapper.insert(grade);
        if(grade.getGrade()==0){
            QueryWrapper<Grade> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.lambda().eq(Grade::getCourseId,grade.getCourseId());
            Integer courseGrades=gradeMapper.selectCount(queryWrapper1);        //课程评价总数

            QueryWrapper<Grade> queryWrapper2=new QueryWrapper<>();
            queryWrapper2.lambda()
                    .eq(Grade::getCourseId,grade.getCourseId())
                    .eq(Grade::getGrade,0);
            Integer courseLikeGrades=gradeMapper.selectCount(queryWrapper2);
            NumberFormat percent=NumberFormat.getPercentInstance();
            percent.setMaximumFractionDigits(0);
            percent.setMinimumFractionDigits(0);
            String likeRate=percent.format((float)courseLikeGrades/courseGrades);
            courseMapper.updateLikeGrades(grade.getCourseId(),likeRate);
            // System.out.println(courseGrades);
            //System.out.println(courseLikeGrades);
        }
        return true;
    }

    public String getCourseLikeGrades(Long courseId){
        Course course=courseMapper.selectById(courseId);
        if(course==null){
            return null;
        }
        return course.getLikeRate();
    }

}

